<template>
  <div :class="['message', `${messageRole}-message`]">
    <!-- 头像 -->
    <div class="message-avatar">
      <img :src="userIcon" alt="用户" style="width: 36px; height: 36px;" v-if="messageRole === 'user'"/>
      <img :src="logoIcon" alt="arcCHAT" style="width: 36px; height: 36px;" v-else/>
    </div>

    <!-- 内容 -->
    <div class="message-content">
      <!-- 角色标签 -->
      <div class="message-header">
        <span class="message-role">
          {{ messageRole === 'user' ? '你' : 'arcCHAT' }}
        </span>
        <span class="message-time">
          {{ formatTime(message.created_at) }}
        </span>
      </div>

      <!-- 思考过程(如果存在) -->
      <div v-if="thinkingContent" class="thinking-section">
        <a-collapse 
          v-model:activeKey="thinkingExpanded" 
          ghost
          :bordered="false"
          class="thinking-collapse"
        >
          <a-collapse-panel key="1" class="thinking-panel">
            <template #header>
              <span class="thinking-header">
                <bulb-outlined style="color: #faad14; margin-right: 6px;" />
                思考过程
              </span>
            </template>
            <div class="thinking-content" v-html="formattedThinking"></div>
          </a-collapse-panel>
        </a-collapse>
      </div>

      <!-- 文本内容 -->
      <div class="message-text" v-html="formattedContent"></div>
      
      <!-- 搜索结果HTML内容（如果消息中包含HTML） -->
      <div v-if="hasSearchResults" class="search-results-wrapper" v-html="searchResultsHtml" ref="searchResultsRef"></div>

      <!-- 3D结构查看器 -->
      <div v-if="structureViewerVisible" class="structure-viewer-wrapper">
        <a-card :title="`3D结构查看器 - ${currentStructureAccession}`" style="margin-top: 16px;">
          <template #extra>
            <a-button type="text" size="small" @click="closeStructureViewer">关闭</a-button>
          </template>
          <div :id="structureViewerId" class="structure-viewer-container"></div>
          <div style="margin-top: 12px;">
            <a-space wrap>
              <a-button @click="setStructureStyle('cartoon')" size="small">Cartoon</a-button>
              <a-button @click="setStructureStyle('stick')" size="small">Stick</a-button>
              <a-button @click="setStructureStyle('sphere')" size="small">Sphere</a-button>
              <a-button @click="setStructureStyle('line')" size="small">Line</a-button>
              <a-button @click="resetStructureView" size="small" type="primary">重置视图</a-button>
            </a-space>
          </div>
          <a-alert 
            message="3D结构由AlphaFold预测生成" 
            type="info" 
            show-icon 
            style="margin-top: 12px;"
          />
        </a-card>
      </div>

      <!-- 意图标签(如果有) -->
      <a-tag v-if="message.intent && message.intent !== 'general_chat'" color="blue" style="margin-top: 8px;">
        {{ intentLabel(message.intent) }}
      </a-tag>

      <!-- 工具调用结果(如果有) -->
      <div v-if="message.tool_calls && Array.isArray(message.tool_calls) && message.tool_calls.length > 0" class="tool-calls">
        <a-divider style="margin: 12px 0;" />
        <div v-for="(toolCall, index) in message.tool_calls" :key="index" class="tool-call-item">
          <div class="tool-call-header">
            <tool-outlined style="color: #409eff; margin-right: 6px;" />
            <span class="tool-call-name">{{ getToolName(toolCall.tool) }}</span>
            <a-tag v-if="toolCall.result && toolCall.result.success !== false" color="success" size="small" style="margin-left: 8px;">
              成功
            </a-tag>
            <a-tag v-else-if="toolCall.result && toolCall.result.success === false" color="error" size="small" style="margin-left: 8px;">
              失败
            </a-tag>
          </div>
          
          <!-- 工具参数 -->
          <div v-if="toolCall.parameters" class="tool-call-params">
            <a-collapse ghost size="small">
              <a-collapse-panel key="params" header="查看参数">
                <div class="params-content">
                  <div v-for="(value, key) in toolCall.parameters" :key="key" class="param-item">
                    <strong>{{ key }}:</strong> 
                    <span v-if="typeof value === 'string' && value.length > 100">
                      {{ value.substring(0, 100) }}...
                    </span>
                    <span v-else>{{ value }}</span>
                  </div>
                </div>
              </a-collapse-panel>
            </a-collapse>
          </div>
          
          <!-- 工具结果统计 -->
          <div v-if="toolCall.result && toolCall.result.success !== false" class="tool-call-summary">
            <div v-if="toolCall.tool === 'search_protein'" class="summary-item">
              <span class="summary-label">找到结果:</span>
              <span class="summary-value">{{ toolCall.result.result?.total || toolCall.result.total || 0 }} 个</span>
            </div>
            <div v-else-if="toolCall.tool === 'blast_sequence_search'" class="summary-item">
              <span class="summary-label">匹配数:</span>
              <span class="summary-value">{{ toolCall.result.result?.total_hits || toolCall.result.total_hits || 0 }} 个</span>
              <span v-if="toolCall.result.result?.query_length" class="summary-label" style="margin-left: 12px;">
                查询长度: {{ toolCall.result.result.query_length }} aa
              </span>
            </div>
            <div v-else-if="toolCall.tool === 'foldseek_structure_search'" class="summary-item">
              <span class="summary-label">匹配数:</span>
              <span class="summary-value">{{ toolCall.result.result?.total_hits || toolCall.result.total_hits || 0 }} 个</span>
            </div>
          </div>
          
          <!-- 错误信息 -->
          <div v-if="toolCall.result && toolCall.result.success === false" class="tool-call-error">
            <a-alert
              :message="toolCall.result.error || '工具执行失败'"
              type="error"
              size="small"
              :show-icon="true"
            />
          </div>
        </div>
      </div>
      
      <!-- 兼容旧格式（单个tool_calls对象） -->
      <div v-else-if="message.tool_calls && typeof message.tool_calls === 'object' && !Array.isArray(message.tool_calls)" class="tool-calls">
        <a-divider style="margin: 12px 0;" />
        <div class="tool-call-label">
          <tool-outlined /> 调用工具: {{ message.tool_calls.tool }}
        </div>
      </div>

      <!-- 引用信息(如果有) -->
      <div v-if="message.citations && message.citations.length > 0" class="citations">
        <a-divider style="margin: 12px 0;" />
        <a-collapse ghost>
          <a-collapse-panel header="📚 引用来源">
            <div v-for="(cite, index) in message.citations" :key="index" class="citation-item">
              <strong>[{{ cite.index }}]</strong> {{ cite.doc_title }}
              <div v-if="cite.author || cite.source" style="font-size: 12px; color: #909399; margin-top: 4px;">
                <span v-if="cite.author">{{ cite.author }}</span>
                <span v-if="cite.source">, {{ cite.source }}</span>
                <span v-if="cite.page">, 第{{ cite.page }}页</span>
              </div>
            </div>
          </a-collapse-panel>
        </a-collapse>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { ToolOutlined, BulbOutlined } from '@ant-design/icons-vue'
import { marked } from 'marked'
import { message } from 'ant-design-vue'
import axios from 'axios'
import config from '../../config/env'
import userIcon from './user.svg'
import logoIcon from './logo.png'

const props = defineProps({
  message: {
    type: Object,
    required: true
  }
})

// 思考过程折叠状态
const thinkingExpanded = ref([])

// 确保role字段正确（规范化role值）
const messageRole = computed(() => {
  const role = props.message?.role
  // 如果role是'user'或'assistant'，直接返回
  if (role === 'user' || role === 'assistant') {
    return role
  }
  // 如果role无效，记录警告并默认返回'assistant'
  console.warn('消息role字段无效:', role, '消息内容:', props.message?.content?.substring(0, 50))
  return 'assistant'
})

// 3D结构查看器相关状态
const structureViewerVisible = ref(false)
const currentStructureId = ref(null)
const currentStructureAccession = ref('')
const structureViewerId = ref(`structure-viewer-${Date.now()}-${Math.random()}`)
let structureViewer = null
const searchResultsRef = ref(null)

// 提取思考过程和正式内容
const extractThinkingAndContent = (text) => {
  if (!text) return { thinking: null, content: text }
  
  // 格式1（优先）: <answer>...</answer> - answer外的就是思考过程
  const answerTagMatch = text.match(/<answer>([\s\S]*?)<\/answer>/i)
  if (answerTagMatch) {
    const answerContent = answerTagMatch[1].trim()
    const beforeAnswer = text.substring(0, text.indexOf('<answer>')).trim()
    const afterAnswer = text.substring(text.indexOf('</answer>') + 9).trim()
    
    // 组合answer前后的内容作为正式回答
    let finalContent = answerContent
    if (afterAnswer) {
      finalContent = answerContent + '\n\n' + afterAnswer
    }
    
    return {
      thinking: beforeAnswer || null,
      content: finalContent
    }
  }
  
  // 格式2: <thinking>...</thinking>
  const thinkingTagMatch = text.match(/<thinking>([\s\S]*?)<\/thinking>/i)
  if (thinkingTagMatch) {
    return {
      thinking: thinkingTagMatch[1].trim(),
      content: text.replace(/<thinking>[\s\S]*?<\/thinking>/i, '').trim()
    }
  }
  
  // 格式3: 【思考】...【/思考】或 [思考]...[/思考]
  const thinkingBracketMatch = text.match(/[【\[]思考[】\]]([\s\S]*?)[【\[][\/\/]?思考[】\]]/i)
  if (thinkingBracketMatch) {
    return {
      thinking: thinkingBracketMatch[1].trim(),
      content: text.replace(/[【\[]思考[】\]][\s\S]*?[【\[][\/\/]?思考[】\]]/i, '').trim()
    }
  }
  
  // 格式4: "让我思考一下..."开头的段落
  const thinkingPrefixMatch = text.match(/^(让我[想思考]+.*?[\n\r]+)([\s\S]*)/i)
  if (thinkingPrefixMatch && thinkingPrefixMatch[1].length < 200) {
    return {
      thinking: thinkingPrefixMatch[1].trim(),
      content: thinkingPrefixMatch[2].trim()
    }
  }
  
  return { thinking: null, content: text }
}

// 思考内容
const thinkingContent = computed(() => {
  const { thinking } = extractThinkingAndContent(props.message.content)
  return thinking
})

// 格式化思考过程
const formattedThinking = computed(() => {
  if (!thinkingContent.value) return ''
  
  try {
    return marked(thinkingContent.value, {
      breaks: true,
      gfm: true
    })
  } catch (e) {
    return thinkingContent.value.replace(/\n/g, '<br>')
  }
})

// 清理JSON格式的工具调用信息
const cleanContent = (text) => {
  if (!text) return text
  
  // 移除JSON格式的工具调用信息
  let cleaned = text
  
  // 移除类似 {"name": "protein_search", "arguments": {...}} 的内容（更精确的匹配）
  cleaned = cleaned.replace(/\{\s*"name"\s*:\s*"[^"]+"\s*,\s*"arguments"\s*:\s*\{[^}]*\}\s*\}/gi, '')
  cleaned = cleaned.replace(/\{\s*"name"\s*:\s*"[^"]+"\s*,\s*"arguments"\s*:\s*\{[^{}]*\{[^}]*\}[^}]*\}\s*\}/gi, '')
  
  // 移除可能的残留文本（如"ington"等，只在开头匹配）
  cleaned = cleaned.replace(/^[a-z]{1,20}\s+/i, '').trim()
  
  // 清理多余的空白字符（但保留换行）
  cleaned = cleaned.replace(/[ \t]+/g, ' ')
  
  // 清理多余的空行（保留单个换行）
  cleaned = cleaned.replace(/\n\s*\n+/g, '\n\n').trim()
  
  return cleaned
}

// 检查消息中是否包含搜索结果HTML
const hasSearchResults = computed(() => {
  const content = props.message.content || ''
  return content.includes('search-results-container') || content.includes('class="search-results')
})

// 提取搜索结果HTML
const searchResultsHtml = computed(() => {
  const content = props.message.content || ''
  if (!hasSearchResults.value) return ''
  
  // 查找所有search-results-container的开始位置
  // 可能有多个容器，需要找到所有的
  const containers = []
  let searchIndex = 0
  
  while (true) {
    const containerStart = content.indexOf('<div class="search-results-container"', searchIndex)
    if (containerStart === -1) break
    
    // 从开始位置向后查找，匹配对应的结束标签
    // 需要计算div的嵌套深度
    let depth = 0
    let endPos = -1
    
    for (let i = containerStart; i < content.length; i++) {
      // 检查是否是div开始标签（需要检查是否是完整的标签）
      const divStart = content.substr(i, 4)
      if (divStart === '<div') {
        // 确保是完整的div标签开始（检查后面是否有空格、>或class等）
        const nextChar = content[i + 4]
        if (nextChar === ' ' || nextChar === '>') {
          depth++
        }
      } else if (content.substr(i, 6) === '</div>') {
        depth--
        if (depth === 0) {
          endPos = i + 6
          break
        }
      }
    }
    
    if (endPos > containerStart) {
      containers.push(content.substring(containerStart, endPos))
      searchIndex = endPos
    } else {
      break
    }
  }
  
  if (containers.length > 0) {
    const html = containers.join('')
    const buttonCount = (html.match(/view-3d-structure-btn/g) || []).length
    console.log(`提取到 ${containers.length} 个搜索结果容器，HTML长度: ${html.length}, 包含按钮数: ${buttonCount}`)
    return html
  }
  
  console.warn('未找到搜索结果HTML结构')
  return ''
})

// 格式化内容(支持Markdown和HTML)
const formattedContent = computed(() => {
  const { content } = extractThinkingAndContent(props.message.content)
  if (!content) return ''
  
  // 清理JSON格式的工具调用信息
  let cleanedContent = cleanContent(content)
  
  // 移除搜索结果HTML部分（我们将单独显示）
  // 使用与提取相同的逻辑
  const containerStart = cleanedContent.indexOf('<div class="search-results-container"')
  if (containerStart !== -1) {
    let depth = 0
    let startTagFound = false
    let endPos = -1
    
    for (let i = containerStart; i < cleanedContent.length; i++) {
      if (cleanedContent.substr(i, 4) === '<div') {
        depth++
        startTagFound = true
      } else if (cleanedContent.substr(i, 6) === '</div>') {
        depth--
        if (depth === 0 && startTagFound) {
          endPos = i + 6
          break
        }
      }
    }
    
    if (endPos > containerStart) {
      cleanedContent = cleanedContent.substring(0, containerStart) + cleanedContent.substring(endPos)
    }
  }
  
  try {
    // 使用marked渲染Markdown
    return marked(cleanedContent, {
      breaks: true,
      gfm: true
    })
  } catch (e) {
    // 如果解析失败,返回原文本
    return cleanedContent.replace(/\n/g, '<br>')
  }
})

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  
  const date = new Date(timestamp)
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  
  return `${hours}:${minutes}`
}

// 意图标签
const intentLabel = (intent) => {
  const labels = {
    'search_protein': '🔍 蛋白质搜索',
    'blast_sequence_search': '🧬 BLAST比对',
    'foldseek_structure_search': '⚛️ 结构比对',
    'blast_sequence': '🧬 BLAST比对',
    'compare_structure': '⚛️ 结构比对',
    'knowledge_qa': '📚 知识问答',
    'general_chat': '💬 普通对话'
  }
  return labels[intent] || intent
}

// 工具名称显示
const getToolName = (toolName) => {
  const names = {
    'search_protein': '🔍 蛋白质搜索',
    'blast_sequence_search': '🧬 BLAST序列搜索',
    'foldseek_structure_search': '⚛️ Foldseek结构搜索'
  }
  return names[toolName] || toolName
}

// 加载3Dmol.js库
const load3DMol = () => {
  return new Promise((resolve, reject) => {
    if (window.$3Dmol) {
      resolve()
      return
    }
    
    const script = document.createElement('script')
    script.src = 'https://3Dmol.csb.pitt.edu/build/3Dmol-min.js'
    script.onload = () => resolve()
    script.onerror = () => reject(new Error('Failed to load 3Dmol.js'))
    document.head.appendChild(script)
  })
}

// 加载3D结构
const loadStructure = async (proteinId, accession) => {
  console.log('开始加载3D结构:', { proteinId, accession }) // 调试日志
  
  try {
    currentStructureId.value = proteinId
    currentStructureAccession.value = accession || `ID: ${proteinId}`
    structureViewerVisible.value = true
    
    // 等待DOM更新（多等待一次，确保Card组件完全渲染）
    await nextTick()
    await new Promise(resolve => setTimeout(resolve, 100)) // 额外等待100ms
    
    // 加载3Dmol.js库
    console.log('加载3Dmol.js库...')
    await load3DMol()
    console.log('3Dmol.js库加载完成')
    
    // 获取PDB文件
    console.log('获取PDB文件，proteinId:', proteinId)
    const response = await axios.get(`${config.API_BASE_URL}/pdb/${proteinId}`)
    const pdbData = response.data.pdb_content
    console.log('PDB文件获取成功，长度:', pdbData.length)
    
    // 获取容器元素
    const element = document.getElementById(structureViewerId.value)
    if (!element) {
      console.error('找不到结构查看器容器，ID:', structureViewerId.value)
      throw new Error('Structure viewer container not found')
    }
    
    console.log('找到容器元素:', element)
    
    // 清理旧的viewer
    if (structureViewer) {
      structureViewer.clear()
      structureViewer = null
    }
    
    // 创建新的viewer
    console.log('创建3Dmol查看器...')
    structureViewer = window.$3Dmol.createViewer(element, {
      backgroundColor: '#263238'
    })
    
    console.log('添加PDB模型...')
    structureViewer.addModel(pdbData, 'pdb')
    structureViewer.setStyle({}, { cartoon: { color: 'spectrum' } })
    structureViewer.zoomTo()
    structureViewer.render()
    
    console.log('3D结构渲染完成')
    message.success('3D结构加载成功')
  } catch (error) {
    console.error('加载3D结构失败:', error)
    message.error('加载3D结构失败: ' + (error.response?.data?.detail || error.message))
    structureViewerVisible.value = false
  }
}

// 设置结构样式
const setStructureStyle = (style) => {
  if (!structureViewer) return
  
  structureViewer.setStyle({}, {})
  switch (style) {
    case 'cartoon':
      structureViewer.setStyle({}, { cartoon: { color: 'spectrum' } })
      break
    case 'stick':
      structureViewer.setStyle({}, { stick: { colorscheme: 'Jmol' } })
      break
    case 'sphere':
      structureViewer.setStyle({}, { sphere: { colorscheme: 'Jmol' } })
      break
    case 'line':
      structureViewer.setStyle({}, { line: { colorscheme: 'Jmol' } })
      break
  }
  structureViewer.render()
}

// 重置视图
const resetStructureView = () => {
  if (!structureViewer) return
  structureViewer.zoomTo()
  structureViewer.render()
}

// 关闭结构查看器
const closeStructureViewer = () => {
  structureViewerVisible.value = false
  if (structureViewer) {
    structureViewer.clear()
    structureViewer = null
  }
}

// 监听搜索结果HTML中的按钮点击事件
const setupStructureViewerButtons = () => {
  if (!searchResultsRef.value) return
  
  try {
    // 使用事件委托，监听整个容器上的点击事件
    // 这样即使HTML是动态插入的也能工作
    const container = searchResultsRef.value
    
    // 移除旧的监听器（如果存在）
    if (container.dataset.listenerAttached === 'true') {
      return
    }
    
    // 标记已绑定事件
    container.dataset.listenerAttached = 'true'
    
    // 添加点击事件监听器（事件委托）
    container.addEventListener('click', (e) => {
      // 检查点击的是否是"查看3D结构"按钮
      const button = e.target.closest('.view-3d-structure-btn')
      if (button) {
        e.preventDefault()
        e.stopPropagation()
        
        const proteinId = button.getAttribute('data-protein-id')
        const accession = button.getAttribute('data-accession')
        
        console.log('点击查看3D结构按钮:', { proteinId, accession }) // 调试日志
        
        if (proteinId) {
          loadStructure(parseInt(proteinId), accession)
        } else {
          console.error('未找到proteinId属性')
          message.error('无法获取蛋白质ID')
        }
      }
    })
    
    console.log('3D结构查看器按钮事件已绑定，找到按钮数量:', container.querySelectorAll('.view-3d-structure-btn').length)
  } catch (error) {
    console.error('设置3D结构查看器按钮失败:', error)
  }
}

// 监听消息内容变化，设置按钮事件
watch(() => [hasSearchResults.value, searchResultsRef.value], () => {
  if (hasSearchResults.value && searchResultsRef.value) {
    // 使用setTimeout确保DOM完全更新
    setTimeout(() => {
      setupStructureViewerButtons()
    }, 100)
  }
}, { immediate: true })

// 监听props.message.content的变化，确保HTML更新后重新绑定事件
watch(() => props.message.content, () => {
  if (hasSearchResults.value) {
    // 清除之前的标记，重新绑定
    if (searchResultsRef.value) {
      searchResultsRef.value.dataset.listenerAttached = 'false'
    }
    setTimeout(() => {
      setupStructureViewerButtons()
    }, 200)
  }
}, { flush: 'post' })

// 组件挂载时设置
onMounted(() => {
  if (hasSearchResults.value) {
    setTimeout(() => {
      setupStructureViewerButtons()
    }, 300)
  }
})

// 组件卸载时清理
onUnmounted(() => {
  if (structureViewer) {
    structureViewer.clear()
    structureViewer = null
  }
})
</script>

<style scoped>
.message {
  display: flex;
  gap: 12px;
  animation: fadeIn 0.3s;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.user-message {
  flex-direction: row-reverse;
  margin-left: auto;
  max-width: 70%;
}

.assistant-message {
  flex-direction: row;
  margin-right: auto;
  max-width: 85%;
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  flex-shrink: 0;
  background: #e8f4fd;
}

.user-message .message-avatar {
  background: #f0f5ff;
}

.message-content {
  flex: 1;
  padding: 14px 18px;
  border-radius: 12px;
  background: #fff;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
  word-wrap: break-word;
  border: 1px solid #f0f0f0;
}

.user-message .message-content {
  background: #f0f5ff;
  color: #2c3e50;
  border: 1px solid #d6e4ff;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.message-role {
  font-weight: 600;
  font-size: 14px;
}

.user-message .message-role {
  color: #2c3e50;
}

.message-time {
  font-size: 12px;
  color: #909399;
}

.user-message .message-time {
  color: #909399;
}

.message-text {
  font-size: 14px;
  line-height: 1.7;
  color: #2c3e50;
}

.user-message .message-text {
  color: #2c3e50;
}

/* Markdown样式 */
:deep(.message-text p) {
  margin: 8px 0;
}

:deep(.message-text code) {
  background: #f7f8fa;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  border: 1px solid #e8e8e8;
}

:deep(.message-text pre) {
  background: #f7f8fa;
  padding: 14px;
  border-radius: 8px;
  overflow-x: auto;
  margin: 12px 0;
  border: 1px solid #e8e8e8;
}

:deep(.message-text pre code) {
  background: none;
  padding: 0;
}

:deep(.message-text ul),
:deep(.message-text ol) {
  margin: 8px 0;
  padding-left: 24px;
}

:deep(.message-text li) {
  margin: 4px 0;
}

:deep(.message-text strong) {
  font-weight: 600;
}

:deep(.message-text a) {
  color: #409eff;
  text-decoration: none;
}

:deep(.message-text a:hover) {
  text-decoration: underline;
}

/* 工具调用 */
.tool-calls {
  margin-top: 8px;
}

.tool-call-item {
  margin-bottom: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
}

.tool-call-item:last-child {
  margin-bottom: 0;
}

.tool-call-header {
  display: flex;
  align-items: center;
  font-size: 13px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 8px;
}

.tool-call-name {
  flex: 1;
}

.tool-call-label {
  font-size: 12px;
  color: #606266;
  display: flex;
  align-items: center;
  gap: 6px;
}

.tool-call-params {
  margin-top: 8px;
}

.params-content {
  font-size: 12px;
  color: #606266;
}

.param-item {
  margin: 4px 0;
  padding: 4px 0;
}

.param-item strong {
  color: #2c3e50;
  margin-right: 6px;
}

.tool-call-summary {
  margin-top: 8px;
  padding: 8px;
  background: #e6f7ff;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.summary-item {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.summary-label {
  color: #606266;
  margin-right: 6px;
}

.summary-value {
  color: #409eff;
  font-weight: 600;
}

.tool-call-error {
  margin-top: 8px;
}

/* 思考过程 */
.thinking-section {
  margin-bottom: 12px;
}

.thinking-collapse {
  background: #fffbf0;
  border: 1px solid #ffe7ba;
  border-radius: 6px;
  overflow: hidden;
}

:deep(.thinking-panel) {
  border: none !important;
}

:deep(.thinking-panel .ant-collapse-header) {
  padding: 8px 12px !important;
  background: #fff9e6;
  font-size: 13px;
  color: #d48806;
  font-weight: 500;
}

:deep(.thinking-panel .ant-collapse-header:hover) {
  background: #fff7db !important;
}

:deep(.thinking-panel .ant-collapse-content) {
  border-top: 1px solid #ffe7ba;
}

:deep(.thinking-panel .ant-collapse-content-box) {
  padding: 12px !important;
  background: #fffbf0;
}

.thinking-header {
  display: flex;
  align-items: center;
  font-size: 13px;
}

.thinking-content {
  font-size: 13px;
  line-height: 1.6;
  color: #8c6d1f;
}

.thinking-content p {
  margin: 6px 0;
}

/* 用户消息中的思考区域 */
.user-message .thinking-collapse {
  background: #e6f4ff;
  border-color: #91caff;
}

.user-message :deep(.thinking-panel .ant-collapse-header) {
  background: #d6e4ff;
  color: #0958d9;
}

.user-message :deep(.thinking-panel .ant-collapse-content-box) {
  background: #e6f4ff;
}

.user-message .thinking-content {
  color: #0958d9;
}

/* 引用 */
.citations {
  margin-top: 8px;
}

.citation-item {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.citation-item:last-child {
  border-bottom: none;
}

/* 搜索结果HTML样式 */
.search-results-wrapper {
  margin-top: 12px;
}

:deep(.search-results-container) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  transition: box-shadow 0.3s ease;
}

:deep(.search-results-container):hover {
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

:deep(.search-results-header) {
  font-weight: 600;
}

:deep(.search-results-content) {
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #fafafa;
}

:deep(.search-results-content::-webkit-scrollbar) {
  width: 6px;
}

:deep(.search-results-content::-webkit-scrollbar-track) {
  background: #fafafa;
}

:deep(.search-results-content::-webkit-scrollbar-thumb) {
  background: #c1c1c1;
  border-radius: 3px;
}

:deep(.search-results-content::-webkit-scrollbar-thumb:hover) {
  background: #a8a8a8;
}

:deep(.search-results-content table) {
  font-size: 13px;
}

:deep(.search-results-content table th) {
  font-weight: 600;
  background: #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 1;
}

:deep(.search-results-content table tr:hover) {
  background: #f0f7ff !important;
  cursor: pointer;
}

:deep(.search-results-content table a) {
  color: #409eff;
  text-decoration: none;
  transition: color 0.2s;
}

:deep(.search-results-content table a:hover) {
  color: #66b1ff;
  text-decoration: underline;
}

/* 3D结构查看器样式 */
.structure-viewer-wrapper {
  margin-top: 16px;
}

.structure-viewer-container {
  width: 100%;
  height: 400px;
  position: relative;
  background: #263238;
  border-radius: 6px;
  overflow: hidden;
}

:deep(.view-3d-structure-btn:hover) {
  background: #73d13d !important;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(82, 196, 26, 0.3);
  transition: all 0.2s ease;
}
</style>

